/**
 * @Author: hiram
 * @Date: 2020/11/12 17:50
 */
package main

import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"path"
)

type httpsHandler struct {
}

func addTrust(pool *x509.CertPool, path string) {
	aCrt, err := ioutil.ReadFile(path)
	if err != nil {
		fmt.Println("ReadFile err:", err)
		return
	}
	pool.AppendCertsFromPEM(aCrt)

}

func (*httpsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "golang https server!!!")
}

var rootPath = "C:/Users/hiram.zhao/go/src/gitee.com/gbat"

func main() {
	pool := x509.NewCertPool()
	// 这里是加载客户端提供的证书，最好是加载客户端提供的根证书
	addTrust(pool, path.Join(rootPath, "cnbfbc2_go/static/ssl/ca.crt"))
	addTrust(pool, path.Join(rootPath, "cnbfbc2_go/static/ssl/ville_pem.crt"))

	s := &http.Server{
		Addr:    ":8099",
		Handler: &httpsHandler{},
		TLSConfig: &tls.Config{
			ClientCAs: pool,
			//ClientAuth: tls.RequireAndVerifyClientCert,
		},
	}

	if err := s.ListenAndServeTLS(path.Join(rootPath, "cnbfbc2_go/static/ssl/server.crt"), path.Join(rootPath, "cnbfbc2_go/static/ssl/server.key")); err != nil {
		log.Fatal("ListenAndServeTLS err:", err)
	}
}
